<template>
  <el-dialog
    v-model="visible"
    class="component-coupon-add-or-update"
    :title="dataForm.couponId ? $t('marketing.modifyCoupon') : $t('marketing.newCoupon')"
    :append-to-body="true"
    :close-on-click-modal="false"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      :label-width="$t('language') === 'English' ? '150px' : '100px'"
      @submit.prevent
      @keyup.enter="onSubmit()"
    >
      <el-form-item
        :label="$t('marketing.couponName')"
        prop="couponName"
      >
        <el-input
          v-model.trim="dataForm.couponName"
          maxlength="20"
          show-word-limit
          :placeholder="$t('marketing.couponName')"
          :disabled="dataForm.couponId !== 0"
        />
      </el-form-item>
      <!-- 投放状态 -->
      <el-form-item
        :label="$t('coupon.launchStatus')"
        prop="putonStatus"
      >
        <el-radio-group
          v-model="dataForm.putonStatus"
          :disabled="dataForm.putonStatus < 0"
        >
          <el-radio :label="0">
            {{ $t('coupon.waitAutoLaunch') }}
            <el-tooltip
              class="item"
              effect="light"
              placement="top"
            >
              <template #content>
                <div>{{ $t('coupon.launchTip') }}</div>
              </template>
              <span>
                <el-icon><QuestionFilled /></el-icon>
              </span>
            </el-tooltip>
          </el-radio>
          <el-radio :label="1">
            {{ $t('coupon.launched') }}
          </el-radio>
          <el-radio :label="2">
            {{ $t('coupon.waitLaunch') }}
          </el-radio>
          <el-radio
            :label="-1"
            :disabled="true"
          >
            {{ $t('coupon.cancelLaunch') }}
            <el-tooltip
              class="item"
              effect="light"
              placement="top"
            >
              <template #content>
                <div>{{ $t('coupon.launchTip1') }}</div>
              </template>
              <span>
                <el-icon><QuestionFilled /></el-icon>
              </span>
            </el-tooltip>
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 投放时间 -->
      <el-form-item
        v-if="dataForm.putonStatus === 0"
        :label="$t('coupon.timeToMarket')"
        prop="launchTime"
      >
        <el-date-picker
          v-model="dataForm.launchTime"
          value-format="YYYY-MM-DD"
          type="date"
          :placeholder="$t('coupon.chooseLaunchTime')"
          style="width: 156px"
        />
        <el-time-select
          v-model="launchTimeValue"
          start="00:00"
          step="00:30"
          end="23:30"
          style="width: 110px"
          :class="{'time-select': true, 'time-select-clear': !!launchTimeValue}"
          :placeholder="$t('user.startDate')"
        />
      </el-form-item>
      <!-- 优惠券类型 -->
      <el-form-item
        :label="$t('coupon.couponType')"
        prop="couponType"
      >
        <el-radio-group
          v-model="dataForm.couponType"
          :disabled="putonStatus !== 0 && dataForm.couponId !== 0 && isFlag"
        >
          <el-radio :label="1">
            {{ $t('coupon.voucher') }}
          </el-radio>
          <el-radio :label="2">
            {{ $t('coupon.discountCoupon') }}
          </el-radio>
          <!-- <el-radio :label="3">兑换券</el-radio> -->
        </el-radio-group>
      </el-form-item>
      <!-- 获取方式 -->
      <el-form-item
        :label="$t('coupon.methodObtaining')"
        prop="getWay"
      >
        <el-radio-group
          v-model="dataForm.getWay"
          :disabled="dataForm.putonStatus < 0"
        >
          <el-radio :label="0">
            {{ $t('coupon.receiveDirectly') }}
          </el-radio>
          <el-radio :label="1">
            {{ $t('coupon.exchangeOrDistribution') }}
            <el-tooltip
              class="item"
              effect="light"
              placement="top"
            >
              <template #content>
                <div>{{ $t('coupon.getWayTip') }}</div>
              </template>
              <span>
                <el-icon><QuestionFilled /></el-icon>
              </span>
            </el-tooltip>
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        :label="$t('marketing.conditionsOfUse')"
        prop="cashCondition"
      >
        {{ $t('marketing.fullConsumption') }}
        <el-input
          v-model="dataForm.cashCondition"
          :placeholder="$t('marketing.conditionsOfUse')"
          type="number"
          min="0"
          :disabled="dataForm.couponId !== 0 && isFlag"
          @change="cashConditionChange"
        >
          <template #append>
            {{ $t('admin.dollar') }}
          </template>
        </el-input>
      </el-form-item>
      <el-form-item
        v-if="dataForm.couponType === 1"
        :label="$t('marketing.reductionAmount')"
        prop="reduceAmount"
      >
        <el-input
          v-model="dataForm.reduceAmount"
          :placeholder="$t('marketing.reductionAmount')"
          type="number"
          :disabled="dataForm.couponId !== 0 && isFlag"
          :min="0.01"
          :step="0.01"
          :max="99999"
          @blur="checkNumber(1)"
        >
          <template #append>
            {{ $t('admin.dollar') }}
          </template>
        </el-input>
      </el-form-item>
      <el-form-item
        v-if="dataForm.couponType === 2"
        :label="$t('marketing.discountAmount')"
        prop="couponDiscount"
      >
        <el-input
          v-model="dataForm.couponDiscount"
          :placeholder="$t('marketing.pleaseEnterDiscount')"
          type="number"
          :disabled="dataForm.couponId !== 0 && isFlag"
          min="0.01"
          :step="0.01"
          @input="checkNumber(2)"
        >
          <template #append>
            {{ $t('marketing.fold') }}
          </template>
        </el-input>
      </el-form-item>
      <el-form-item
        :label="$t('coupon.effectiveType')"
        prop="validTimeType"
      >
        <el-radio-group
          v-model="dataForm.validTimeType"
          :disabled="dataForm.couponId !== 0 && isFlag"
        >
          <el-radio :label="1">
            {{ $t('marketing.fixedTime') }}
          </el-radio>
          <el-radio :label="2">
            {{ $t('marketing.effectiveAfterReceipt') }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        v-if="dataForm.validTimeType === 1"
        :label="$t('coupon.startTime')"
        prop="startTime"
      >
        <el-date-picker
          v-model="dataForm.startTime"
          :disabled="dataForm.couponId !== 0 && isFlag"
          value-format="YYYY-MM-DD"
          type="date"
          style="width: 156px"
          :placeholder="$t('marketing.chooseStartTime')"
        />
        <el-time-select
          v-model="startTimeValue"
          start="00:00"
          step="00:30"
          end="23:30"
          :class="{'time-select': true, 'time-select-clear': !!startTimeValue}"
          style="width: 110px"
          :disabled="dataForm.couponId !== 0 && isFlag"
          :placeholder="$t('user.startDate')"
        />
      </el-form-item>
      <el-form-item
        v-if="dataForm.validTimeType === 1"
        :label="$t('coupon.endTime')"
        prop="endTime"
      >
        <el-date-picker
          v-model="dataForm.endTime"
          value-format="YYYY-MM-DD"
          type="date"
          style="width: 156px"
          :disabled="dataForm.overdueStatus === 0"
          :placeholder="$t('marketing.chooseEndTime')"
        />
        <el-time-select
          v-model="endTimeValue"
          start="00:00"
          step="00:30"
          end="23:30"
          :class="{'time-select': true, 'time-select-clear': !!endTimeValue}"
          style="width: 110px"
          :disabled="dataForm.overdueStatus === 0"
          :placeholder="$t('user.endDate')"
        />
      </el-form-item>
      <el-form-item
        v-if="dataForm.validTimeType === 2"
        :label="$t('marketing.afterReceivingTheCoupon')"
        prop="afterReceiveDays"
      >
        <el-input
          v-model="dataForm.afterReceiveDays"
          type="number"
          style="width: 300px"
          :disabled="dataForm.couponId !== 0 && isFlag"
          @input="checkNumber(3)"
        >
          <template #append>
            {{ $t('marketing.effectiveDays') }}
          </template>
        </el-input>
        <el-tooltip
          class="item toolSty"
          effect="dark"
          :content="$t('marketing.maxTimeTip')"
          placement="top"
        >
          <el-icon><InfoFilled /></el-icon>
        </el-tooltip>
      </el-form-item>
      <el-form-item
        v-if="dataForm.validTimeType === 2"
        :label="$t('marketing.validDate')"
        prop="validDays"
      >
        <el-input
          v-model="dataForm.validDays"
          type="number"
          style="width: 300px"
          maxlength="10"
          :disabled="dataForm.couponId !== 0 && isFlag"
          @input="checkNumber(3)"
        >
          <template #append>
            {{ $t('form.day') }}
          </template>
        </el-input>
        <el-tooltip
          class="item toolSty"
          effect="dark"
          :content="$t('marketing.maxTimeTip')"
          placement="top"
        >
          <el-icon><InfoFilled /></el-icon>
        </el-tooltip>
      </el-form-item>
      <!-- 每人限领 -->
      <el-form-item
        :label="$t('marketing.perPerson')"
        prop="limitNum"
      >
        <el-input
          v-model="dataForm.limitNum"
          type="number"
          :disabled="dataForm.putonStatus < 0"
          @change="checkNumber(4)"
        >
          <template #append>
            {{ $t('marketing.piece') }}
          </template>
        </el-input>
      </el-form-item>
      <!-- 库存 -->
      <el-form-item
        :label="$t('marketing.inventory')"
        prop="stocks"
      >
        <el-input
          v-model="dataForm.stocks"
          type="number"
          :disabled="isFlag || putonStatus === 1 || dataForm.putonStatus < 0"
          @change="checkNumber(4)"
        >
          <template #append>
            {{ $t('marketing.piece') }}
          </template>
        </el-input>
      </el-form-item>
      <!-- 适用商品 -->
      <el-form-item
        :label="$t('marketing.applicableGoods')"
        prop="suitableProdType"
      >
        <el-radio-group
          v-model="dataForm.suitableProdType"
          :disabled="isFlag || putonStatus === 1 || dataForm.putonStatus < 0"
        >
          <el-radio :label="0">
            {{ $t('marketing.allProdsPar') }}
          </el-radio>
          <el-radio :label="1">
            {{ $t('marketing.participateInD') }}
          </el-radio>
          <el-radio :label="2">
            {{ $t('marketing.specifiedProduct') }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <div
          v-if="
            !isFlag &&
              +putonStatus !== 1 &&
              dataForm.overdueStatus !== 0 &&
              (dataForm.suitableProdType === 1 || dataForm.suitableProdType === 2)
          "
          class="default-btn"
          @click="prodsSelectHandle()"
        >
          {{ $t('product.select') }}
        </div>
      </el-form-item>
      <!-- 商品 -->
      <el-form-item
        v-if="dataForm.suitableProdType !== 0"
        style="width: 100%"
      >
        <div
          v-for="(couponProd, index) in dataForm.couponProds"
          :key="index"
          style="margin-bottom: 10px"
          class="card-prod"
        >
          <el-card
            :body-style="{ padding: '0px' }"
            style="height: 160px; width: 120px"
          >
            <ImgShow
              :src="couponProd.pic"
              height="104px"
            />
            <div class="card-prod-info-btn">
              <div class="prod-name">
                {{ couponProd.prodName }}
              </div>
              <div
                v-if="dataForm.overdueStatus !== 0 && +putonStatus !== 1 && !isFlag"
                class="del-btn"
              >
                <span @click="deleteProd(index)">{{ $t('text.delBtn') }}</span>
              </div>
            </div>
          </el-card>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <div
          class="default-btn"
          @click="visible = false"
        >
          {{ $t('crud.filter.cancelBtn') }}
        </div>
        <div
          v-if="dataForm.putonStatus > -1"
          type="primary"
          class="default-btn primary-btn"
          @click="onSubmit()"
        >
          {{ $t('crud.filter.submitBtn') }}
        </div>
      </div>
    </template>
    <!-- 商品选择弹窗-->
    <ProdsSelect
      v-if="prodsSelectVisible"
      ref="prodsSelectRef"
      @refresh-select-prods="selectCouponProds"
    />
  </el-dialog>
</template>

<script setup>
import ProdsSelect from '@/components/prods-select/index.vue'
import { Debounce } from '@/utils/debounce'
import { getDateTimeRange, getParseTime } from '@/utils/datetime'
import { ElMessage } from 'element-plus'
const emit = defineEmits(['refreshDataList'])

const visible = ref(false)
const dataForm = ref({
  couponId: 0,
  couponName: '',
  subTitle: '',
  couponType: 1,
  reduceAmount: 0,
  couponDiscount: 0,
  cashCondition: 0,
  validTimeType: 1,
  launchTime: null,
  startTime: null,
  endTime: null,
  afterReceiveDays: 0,
  validDays: 1,
  stocks: 1,
  suitableProdType: 0,
  limitNum: 1,
  putonStatus: 0,
  couponProds: [],
  getWay: 0
})
const dataFormRef = ref(null)

const putonStatus = ref(0)
const prodsSelectVisible = ref(false)

// 表单验证
// eslint-disable-next-line no-unused-vars
const validate = (rule, value, callback) => {
  if (!/^[1-9]\d*$|^[1-9]\d*\.\d\d?$|^0\.\d\d?$/.test(value)) {
    callback(new Error($t('live.pleaseEnteThan0')))
  } else if (value >= 10000000000000) {
    callback(new Error($t('live.numberLimit')))
  } else {
    callback()
  }
}
// eslint-disable-next-line no-unused-vars
const validateNumber = (rule, value, callback) => {
  if (!/^[1-9]\d*$/.test(value)) {
    callback(new Error($t('formData.pleaseThan0')))
  } else if (value >= 2147483600) {
    callback(new Error($t('formData.stockLimit')))
  } else {
    callback()
  }
}
// eslint-disable-next-line no-unused-vars
const validateStocks = (rule, value, callback) => {
  if (value === 0 && dataForm.value.couponId) {
    callback()
  } else if (!/^[1-9]\d*$/.test(value)) {
    callback(new Error($t('formData.pleaseThan0')))
  } else if (value >= 2147483600) {
    callback(new Error($t('formData.stockLimit')))
  } else {
    callback()
  }
}
// eslint-disable-next-line no-unused-vars
const validateeDays = (rule, value, callback) => {
  if (!/^[0-9]\d*$/.test(value)) {
    callback(new Error($t('marketing.pleaseaTo0')))
  } else {
    callback()
  }
}
// eslint-disable-next-line no-unused-vars
const validateeOneDays = (rule, value, callback) => {
  if (!/^[1-9]\d*$/.test(value)) {
    callback(new Error($t('marketing.pleaseaTo1')))
  } else {
    callback()
  }
}
// eslint-disable-next-line no-unused-vars
const discountValidate = (rule, value, callback) => {
  if (!/^[1-9]\d*$|^[1-9]\d*\.\d\d?$|^0\.\d\d?$/.test(value)) {
    callback(new Error($t('marketing.pleaseTo10')))
  } else if (parseInt(value) >= 10 || parseInt(value) < 0) {
    callback(new Error($t('marketing.pleaseTo10')))
  } else {
    callback()
  }
}
// eslint-disable-next-line no-unused-vars
const validateTime = (rule, value, callback) => {
  if (rule.field === 'startTime' && (!startTimeValue.value || !dataForm.value.startTime)) {
    callback(new Error($t('formData.startTimeCannotBeEmpty')))
  }
  if (rule.field === 'endTime' && (!endTimeValue.value || !dataForm.value.endTime)) {
    callback(new Error($t('formData.endTimeCannotBeEmpty')))
  }
  const startTime = dataForm.value.startTime + ' ' + startTimeValue.value + ':00'
  const endTime = dataForm.value.endTime + ' ' + endTimeValue.value + ':00'
  if (Date.parse(startTime) >= Date.parse(endTime)) {
    callback(new Error($t('marketing.timeCanThanOrEqualTo')))
  }
  if (
    dataForm.value.couponId === 0 &&
    rule.field === 'endTime' &&
    new Date() > Date.parse(endTime)
  ) {
    callback(new Error($t('groups.endTime')))
  } else {
    callback()
  }
}
const dataRule = reactive({
  couponName: [
    { required: true, message: $t('marketing.couponNameCannotBeEmpty'), trigger: 'blur' }
  ],
  couponType: [
    { required: true, message: $t('marketing.couponTypeCannotBeEmpty'), trigger: 'blur' }
  ],
  reduceAmount: [
    { required: true, message: $t('marketing.theDedEmpty'), trigger: 'blur' },
    {
      pattern: /^[1-9]\d*$|^[1-9]\d*\.\d\d?$|^0\.\d\d?$/,
      message: $t('marketing.pleaseEnteThan0Positive'),
      trigger: 'blur'
    }
  ],
  limitNum: [
    { required: true, message: $t('marketing.theLimitetBeEmpty'), trigger: 'blur' },
    { validator: validateNumber, trigger: 'blur' }
  ],
  afterReceiveDays: [
    { required: true, message: $t('marketing.collectioeEmpty'), trigger: 'blur' },
    { validator: validateeDays, trigger: 'blur' }
  ],
  validDays: [
    { required: true, message: $t('marketing.effectiveEmpty'), trigger: 'blur' },
    { validator: validateeOneDays, trigger: 'blur' }
  ],
  couponDiscount: [
    { required: true, message: $t('marketing.theDiscouBeEmpty'), trigger: 'blur' },
    { validator: discountValidate, trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: $t('formData.startTimeCannotBeEmpty'), trigger: 'blur' },
    { validator: validateTime, trigger: 'blur' }
  ],
  endTime: [
    { required: true, message: $t('formData.endTimeCannotBeEmpty'), trigger: 'blur' },
    { validator: validateTime, trigger: 'blur' }
  ],
  cashCondition: [
    { required: true, message: $t('marketing.conditionBeEmpty'), trigger: 'blur' },
    { validator: validate, trigger: 'blur' }
  ],
  validTimeType: [{ required: true, message: $t('marketing.effectiveotBeEmpty'), trigger: 'blur' }],
  stocks: [
    { required: true, message: $t('marketing.invenEmpty'), trigger: 'blur' },
    { validator: validateStocks, trigger: 'blur' }
  ],
  suitableProdType: [
    { required: true, message: $t('marketing.applicabltBeEmpty'), trigger: 'blur' }
  ]
})
const isFlag = ref(false)
const launchTimeValue = ref('')
const startTimeValue = ref('')
const endTimeValue = ref('')

watch(visible, val => {
  if (val === false) {
    prodsSelectVisible.value = false
  }
})

// 获取数据列表
const init = couponId => {
  dataForm.value = {
    couponId: 0,
    couponName: '',
    subTitle: '',
    couponType: 1,
    reduceAmount: 0,
    couponDiscount: 0,
    cashCondition: 0,
    validTimeType: 1,
    launchTime: null,
    startTime: null,
    endTime: null,
    afterReceiveDays: 0,
    validDays: 1,
    stocks: 1,
    suitableProdType: 0,
    limitNum: 1,
    putonStatus: 0,
    couponProds: [],
    getWay: 0
  }
  isFlag.value = false
  dataForm.value.couponId = couponId || 0
  putonStatus.value = 0
  visible.value = true
  nextTick(() => {
    // dataFormRef.value?.resetFields()
    const datetimeRange = getDateTimeRange()
    dataForm.value.launchTime = datetimeRange.startTime
    dataForm.value.startTime = datetimeRange.startTime
    dataForm.value.endTime = datetimeRange.endTime
    launchTimeValue.value = datetimeRange.currentTime
    startTimeValue.value = datetimeRange.currentTime
    endTimeValue.value = datetimeRange.currentTime
    if (dataForm.value.couponId) {
      getDataList()
    }
  })
}
const getDataList = () => {
  http({
    url: http.adornUrl(`/admin/coupon/info/${dataForm.value.couponId}`),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    dataForm.value = data
    launchTimeValue.value = dataForm.value.launchTime ? dataForm.value.launchTime.substring(11, dataForm.value.launchTime.length - 3) : ''
    startTimeValue.value = dataForm.value.startTime ? dataForm.value.startTime.substring(11, dataForm.value.startTime.length - 3) : ''
    endTimeValue.value = dataForm.value.endTime ? dataForm.value.endTime.substring(11, dataForm.value.endTime.length - 3) : ''
    dataForm.value.launchTime = getParseTime(dataForm.value.launchTime, '{y}-{m}-{d}')
    dataForm.value.startTime = getParseTime(dataForm.value.startTime, '{y}-{m}-{d}')
    dataForm.value.endTime = getParseTime(dataForm.value.endTime, '{y}-{m}-{d}')
    putonStatus.value = dataForm.value.putonStatus
    if (data.sourceStock !== data.stocks || putonStatus.value === 1 || putonStatus.value === 2) {
      isFlag.value = true
    }
  })
}

// 显示添加指定商品弹框
const prodsSelectRef = ref(null)
const prodsSelectHandle = () => {
  prodsSelectVisible.value = true
  nextTick(() => {
    prodsSelectRef.value?.init(dataFormRef.value?.couponProds)
  })
}
// 删除指定商品
const deleteProd = index => {
  dataForm.value.couponProds.splice(index, 1)
}
// 添加指定商品
const selectCouponProds = prods => {
  if (prods) {
    dataForm.value.couponProds = prods
  }
}
/**
 * 输入框的数据改变时，对值进行校验
 */
const checkNumber = type => {
  if (type === 1) {
    const reduceAmount = parseFloat(dataForm.value.reduceAmount)
    dataForm.value.reduceAmount = formatNumber(reduceAmount)
  }
  if (type === 2) {
    const coupDiscount = dataForm.value.couponDiscount
    // 如果小于零
    if (coupDiscount <= 0) {
      dataForm.value.couponDiscount = 0.1
    }
    if (coupDiscount >= 10) {
      // 如果折扣大于10
      dataForm.value.couponDiscount = 9.9
    }
  }

  if (type === 3) {
    dataForm.value.afterReceiveDays = Number(dataForm.value.afterReceiveDays)
    if (dataForm.value.afterReceiveDays >= 3652) {
      dataForm.value.afterReceiveDays = 3652
    }
    dataForm.value.validDays = Number(dataForm.value.validDays)
    if (dataForm.value.validDays >= 3652) {
      dataForm.value.validDays = 3652
    }
  }
  if (type === 4) {
    dataForm.value.limitNum = Number(dataForm.value.limitNum)
    dataForm.value.stocks = Number(dataForm.value.stocks)
  }
}
// 格式化输入的优惠券减免金额
const formatNumber = number => {
  number = parseFloat(number.toFixed(2))
  if (!number) {
    return
  }
  const maxNumber = 99999.99
  if (number >= maxNumber) {
    return maxNumber
  }
  if (number < 0.01) {
    return 0.01
  }
  return number
}
/**
 * 消费金额最低要求检验
 */
const cashConditionChange = () => {
  const caCondition = parseFloat(dataForm.value.cashCondition)
  dataForm.value.cashCondition = caCondition <= 0.0 ? 0.01 : caCondition
  dataForm.value.cashCondition = caCondition > 9999999.99 ? 9999999.99 : caCondition
}
// 表单提交
const onSubmit = Debounce(() => {
  const launchDate =
    dataForm.value.launchTime && launchTimeValue.value ? dataForm.value.launchTime + ' ' + launchTimeValue.value + ':00' : ''
  const startDate =
    dataForm.value.startTime && startTimeValue.value ? dataForm.value.startTime + ' ' + startTimeValue.value + ':00' : ''
  const endDate =
    dataForm.value.endTime && endTimeValue.value ? dataForm.value.endTime + ' ' + endTimeValue.value + ':00' : ''

  if (dataForm.value.putonStatus === 0) {
    if (dataForm.value.launchTime === null || launchTimeValue.value === null) {
      ElMessage({
        message: $t('coupon.launchTimeTip1'),
        type: 'error',
        duration: 1500
      })
      return
    } else if (Date.parse(launchDate) <= Date.now()) {
      ElMessage({
        message: $t('coupon.launchTimeTip'),
        type: 'error',
        duration: 1500
      })
      return
    }
  }
  if (!dataForm.value.couponProds.length && dataForm.value.suitableProdType) {
    ElMessage({
      message: $t('coupon.pleaseSelectSpecificItem'),
      type: 'error',
      duration: 1500
    })
    return
  }
  if (dataForm.value.validTimeType === 1) {
    if (
      dataForm.value.putonStatus === 0 &&
      (new Date(endDate).getTime() <= new Date(launchDate).getTime() ||
        new Date(endDate).getTime() <= new Date(startDate).getTime())
    ) {
      ElMessage({
        message: $t('coupon.timeTips'),
        type: 'error',
        duration: 1500
      })
      return
    }
  }
  dataFormRef.value.validate(valid => {
    if (valid && checkInput()) {
      if (dataForm.value.suitableProdType) {
        if (!dataForm.value.couponProds.length) {
          ElMessage({
            message: $t('marketing.pleaseSelectAProduct'),
            type: 'error',
            duration: 1500
          })
        }
      }
      const launchTime = dataForm.value.launchTime
      const startTime = dataForm.value.startTime
      const endTime = dataForm.value.endTime
      dataForm.value.launchTime = launchDate
      dataForm.value.startTime = startDate
      dataForm.value.endTime = endDate
      http({
        url: http.adornUrl('/admin/coupon'),
        method: dataForm.value.couponId ? 'put' : 'post',
        data: http.adornData({
          couponId: dataForm.value.couponId || undefined,
          couponName: dataForm.value.couponName,
          getWay: dataForm.value.getWay,
          subTitle: dataForm.value.subTitle.trim() ? dataForm.value.subTitle : '',
          couponType: dataForm.value.couponType,
          reduceAmount: dataForm.value.reduceAmount,
          couponDiscount: dataForm.value.couponDiscount,
          cashCondition: dataForm.value.cashCondition,
          validTimeType: dataForm.value.validTimeType,
          launchTime: dataForm.value.putonStatus === 0 ? dataForm.value.launchTime : null,
          startTime: dataForm.value.startTime,
          endTime: dataForm.value.endTime,
          afterReceiveDays: dataForm.value.afterReceiveDays,
          validDays: dataForm.value.validDays,
          stocks: dataForm.value.stocks,
          suitableProdType: dataForm.value.suitableProdType,
          limitNum: dataForm.value.limitNum,
          putonStatus: dataForm.value.putonStatus,
          couponProds: dataForm.value.couponProds
        })
      }).then(() => {
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            dataForm.value.couponProds = []
            visible.value = false
            emit('refreshDataList')
          }
        })
      })
      dataForm.value.launchTime = launchTime
      dataForm.value.startTime = startTime
      dataForm.value.endTime = endTime
    }
  })
}, 1500)
// 校验输入数据
const checkInput = () => {
  if (dataForm.value.couponType === 1) {
    if (parseFloat(dataForm.value.cashCondition) <= parseFloat(dataForm.value.reduceAmount)) {
      ElMessage.error($t('marketing.amounnCannotBe'))
      return false
    } else if (parseFloat(dataForm.value.reduceAmount) === 0) {
      ElMessage.error($t('marketing.amounnThan0'))
      return false
    }
  }
  return true
}

defineExpose({
  init
})
</script>
<style lang="scss" scoped>
:deep(.el-input__inner) {
  border: none !important;
  padding-left: 0 !important;
}
.component-coupon-add-or-update {
  .card-prod {
    width: 130px;
  }
  .toolSty {
    position: absolute;
    left: -13px;
  }
}
:deep(.time-select.el-select ){
  .el-input .el-select__caret.el-icon{
    display: none;
  }
  &.time-select-clear:hover .el-input .el-select__caret.el-icon{
    display: flex;
  }
}
</style>
